import Typography from "@/pages/OrderModule/common/components/Typography";
import { Alert, Checkbox, Collapse, message, Button, Space } from "antd";
import { DoubleLeftOutlined } from '@ant-design/icons';
import { useEffect, useState } from "react";
import CommonTable from "@/components/CommonTable";
import CommonLoading from "@/components/CommonLoading";
import CommonModal from "@/components/CommonModal";
import IconFont from '@/components/IconFont';
import { cloneDeep, find } from "lodash";
import {useFilterFieldsConfig} from '@/pages/OrderModule/orderList/components/Filter/store.js';
import { updateFieldConfig } from "../../../services";
import styles from "./index.module.less";

const { Panel } = Collapse;

const descEl = (
  <Typography as="s1">
    选择哪个筛选字段类别，哪个就会显示在筛选里
    <Typography as="s1" color="#999">
      (上下可拖动字段排序)
    </Typography>
  </Typography>
);

/** 列表字段设置 */
function EditColumnsCode(props) {
	const { code, filterList, handleOk, handleCancel } = props;
	const [loading, setLoading] = useState(false);
	const [showList, setShowList] = useState(filterList); //更改之后的数据
	const [isOk, setIsOk] = useState(false);
	const [open, setOpen] = useState(false);

	const [expand, setExpand] = useState([]);

  const { checkingMap, updateCheckingMap } = useFilterFieldsConfig();

	useEffect(() => {
		setOpen(true);
		filterList.map(item=>{
			let checkedCount = 0;
			item.childrenNode.map(child=>{
				const bool = checkingMap[child.field]
				child.checked = bool;
				bool && checkedCount ++;
			})
			item.checkedCount = checkedCount;
		})
		setShowList(filterList);
		console.log(filterList, checkingMap)
	}, [])

	const onOk = async () => {
		setLoading(true);
		const obj = {};
		showList.map(item=>{
			item.childrenNode.map(child=>{
				obj[child.field] = child.checked
			})
		})
		const { success, msg = "" } = await updateFieldConfig({
			code,
			param: JSON.stringify(obj)
		});
		setLoading(false);
		if (success) {
			updateCheckingMap({ checkingMap: obj });
			message.success(msg);
			setIsOk(true);
			setOpen(false);
		}
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleOk(showList);
		} else {
			handleCancel();
		}
	}

const handleCheckCollapse = (name) => {
	if(expand.includes(name)){
		setExpand(expand.filter(item=>item != name));
	}else{
		const arr = cloneDeep(expand);
		arr.push(name);
		setExpand(arr);
	}
}

//分组全选
const handleAllCheck = (bool, fatherField) => {
  console.log(bool, fatherField)
	const newList = cloneDeep(showList);
	const obj = find(newList, ['field', fatherField]);
	if(obj){
		obj?.childrenNode?.map(item=>{
			item.checked = bool;
		})
		obj.checkedCount = bool ? obj?.childrenNode?.length : 0
	}
	setShowList(newList);
}

//分组单个勾选
const handleSingleCheck = (bool, fatherField, childField) => {
  const newList = cloneDeep(showList);
	const obj = find(newList, ['field', fatherField]);
	if(obj){
		for(let item of obj?.childrenNode){
			if(item.field == childField){
				item.checked = bool;
        break;
			}
		}
		obj.checkedCount = obj.checkedCount + (bool ? 1 : -1)
	}
	setShowList(newList);
}

const onAscChange = (field, index) => {//field后期扩展入参
	if(!index) return
	const newList = cloneDeep(showList);
	const obj = find(newList, ['field', 'orderSn']);
	if(obj){
		console.log(obj)
		const current = obj.childrenNode[index];
		obj.childrenNode.splice(index-1, 0, current);
		obj.childrenNode.splice(index+1, 1);
		setShowList(newList);
	}
}

const onDescChange = (field, index) => {//field后期扩展入参
	const newList = cloneDeep(showList);
	const obj = find(newList, ['field', 'orderSn']);
	if(obj){
		if(index == obj.childrenNode.length - 1) return;
		const current = obj.childrenNode[index];
		obj.childrenNode.splice(index, 1);
		obj.childrenNode.splice(index+1, 0, current);
		setShowList(newList);
	}
}

	const columns = [
		{
      title: '序号',
			render: (t, r, i) => i + 1
		},
		{
			title: "筛选字段",
			dataIndex: "text",
			width: 200,
			render(v, record) {
				return (<Collapse className={styles.collapse} ghost expandIconPosition="end"
					expandIcon={({ isActive }) => <DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: '12px', color: '#4E5969' }} />}
					onChange={e=>handleCheckCollapse(record.name)}
					activeKey={expand.includes(record.name) ? '1' : ''}
					>
					<Panel header={record.title} key="1">
						{record.childrenNode.map(item=><p key={item.title} style={{lineHeight:'25px'}}>{item.title}</p>)}
					</Panel>
				</Collapse>)
		},
		},
		{
			title: '是否显示',
			dataIndex: "checked",
			width: 150,
			render: (t, record, index) => {
				const groupChecked = record.childrenNode?.every(item=>item.checked);
				return (<div key='allbox'>
					<div key='groupbox'>
						<Checkbox disabled={record.lock} checked={groupChecked} 
					    onChange={e => handleAllCheck(e.target.checked, record.field)} 
							indeterminate={!groupChecked && record.checkedCount} 
							/>
					</div>
						{
							expand.includes(record.name) && record.childrenNode?.map((item,index)=>{
								return (<div className={styles['control-wrapper']} key={index}>
									<Checkbox disabled={record.lock} checked={item.checked} onChange={e => handleSingleCheck(e.target.checked, record.field, item.field)} />
										{
											record.allowSort && (<div className={styles['control-icon-group']}>
												<div className={styles['control-icon']} onClick={() => onAscChange?.(item.field, index)}>
														<IconFont type={'iconarrow-up-copy'}></IconFont>
												</div>
												<div className={styles['control-icon']} onClick={() => onDescChange?.(item.field, index)}>
														<IconFont type={'iconarrow-down-copy'}></IconFont>
												</div>
											</div>)
										}
								</div>)
							})
						}
				</div>)
			}
		}
	];

	const TableProps = {
		data: showList,
		size: "small",
		columns,
		rowKey: "name",
		bordered: true,
		isSortData: true,
		scroll: {
			y: "45vh"
		},
		onDragEnd(val) {
			setShowList(val);
		}
	};

	return (
		<CommonModal
			width="530px"
			title="筛选字段设置"
			open={open}
			onOk={onOk}
			onCancel={onCancel}
			afterClose={afterClose}
			footer={
				<>
					<Button onClick={onCancel}>取消</Button>
					<Button type="primary" onClick={onOk}>
						保存
					</Button>
				</>
			}
		>
			<Alert style={{ marginBottom: "16px" }} message={descEl} />
			<div style={{userSelect:'none'}}>
			  <CommonTable {...TableProps} />
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default EditColumnsCode;
